# api/database.py
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.base import Engine

# 数据库连接字符串
SQLALCHEMY_DATABASE_URL = os.getenv("SQLALCHEMY_DATABASE_URL", "").strip()
# 数据库连接字符串 mysql+mysqlconnector://账号:密码@ip:3306/数据库名

engine: Engine | None = None
SessionLocal = None

if SQLALCHEMY_DATABASE_URL:
    try:
        # 创建数据库引擎
        engine = create_engine(SQLALCHEMY_DATABASE_URL)
        
        # 创建会话工厂
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        print("✅ 数据库连接成功")
    except Exception as e:
        print(f" 数据库连接失败，将跳过数据库功能: {e}")
        engine = None
        SessionLocal = None
else:
    print(" 未配置 SQLALCHEMY_DATABASE_URL，将跳过数据库连接")